package main

import (
	"fmt"
	"sync"
	"time"
)

// Task 是协程池中每个任务需要实现的接口
type Task interface {
	Execute()
}

// ExampleTask 是一个实现了Task接口的示例任务
type ExampleTask struct {
	Num int
}

// Execute 是ExampleTask的执行逻辑
func (e *ExampleTask) Execute() {
	fmt.Printf("Processing task %d\n", e.Num)
	time.Sleep(time.Second) // 模拟任务执行时间
}

// GoroutinePool 是协程池的结构体
type GoroutinePool struct {
	Tasks       chan Task
	concurrency int
	wg          sync.WaitGroup
}

// NewGoroutinePool 创建一个新的协程池
func NewGoroutinePool(concurrency int) *GoroutinePool {
	return &GoroutinePool{
		Tasks:       make(chan Task),
		concurrency: concurrency,
	}
}

// Start 启动协程池
func (gp *GoroutinePool) Start() {
	for i := 0; i < gp.concurrency; i++ {
		gp.wg.Add(1)
		go func() {
			for task := range gp.Tasks {
				task.Execute()
			}
			gp.wg.Done()
		}()
	}
}

// Stop 停止协程池
func (gp *GoroutinePool) Stop() {
	close(gp.Tasks)
	gp.wg.Wait() // 等待所有协程执行完成
}

func main() {
	tasks := 10
	concurrency := 3
	pool := NewGoroutinePool(concurrency)

	// 启动协程池
	pool.Start()

	// 添加任务到协程池
	for i := 0; i < tasks; i++ {
		task := &ExampleTask{Num: i}
		pool.Tasks <- task
	}

	// 停止协程池
	pool.Stop()

	fmt.Println("All tasks finished.")
}
